package io.dubbo.springboot;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;

import java.util.Set;

@Slf4j
public class DubboConfigurationApplicationContextInitializer
        implements ApplicationContextInitializer<ConfigurableApplicationContext>,
        ApplicationListener<ApplicationStartedEvent> {

    private static SpringApplication application;

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        Environment env = applicationContext.getEnvironment();
        Set<Object> sources = application.getSources();
        StringBuilder scanPath = new StringBuilder();
        for (Object source : sources) {
            if (source instanceof Class<?>) {
                scanPath.append(((Class) source).getName().replaceAll("\\.[^\\.]+$", "")).append(",");
            } else {
                log.error("不能识别的入口参数", source);
            }
        }
        if (scanPath.length() > 0) {
            scanPath.deleteCharAt(scanPath.length() - 1);
        }
        AnnotationBeanScanner scanner = new AnnotationBeanScanner();
        scanner.setPackage(scanPath.toString());
        scanner.setApplicationContext(applicationContext);
        applicationContext.addBeanFactoryPostProcessor(scanner);
        applicationContext.getBeanFactory().addBeanPostProcessor(scanner);
        applicationContext.getBeanFactory().registerSingleton("annotationBean", scanner);
    }

    @Override
    public synchronized void onApplicationEvent(ApplicationStartedEvent event) {
        if (application == null) {
            application = event.getSpringApplication();
        }
    }

}
